<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <form action="/" class="searchFrom">
      <van-search
        v-model="searchText"
        shape="round"
        show-action
        placeholder="请输入搜索关键词"
        @focus="isResult = false"
        @cancel="onCancel"
        @search="onSearch"
      />
    </form>

    <!-- 结果 -->
    <search-result  :searchText="searchText" v-if="isResult" />
    <!-- 联想搜索 -->
    <search-suggestion @search="onSearch" :searchText="searchText" v-else-if="searchText" />
    <!-- 搜索历史记录 -->
    <search-history :history="searchHistories" @update-history="UpHistory" @search="SearchResult" v-else/>
  </div>
</template>

<script>
import SearchHistory from '@/views/search/components/search-history.vue'
import SearchResult from '@/views/search/components/search-result.vue'
import SearchSuggestion from '@/views/search/components/search-suggestion.vue'
import { setItem, getItem } from '@/uitls/storage'
export default {
  name: 'SearchPage',
  components: {
    SearchHistory,
    SearchResult,
    SearchSuggestion
  },
  props: {},
  data () {
    return {
      searchText: '', // 搜索框输入的内容
      isResult: false, // 控制组件的显示与隐藏
      searchHistories: getItem('TouTiao_list') || [] // 如果有就取，没有就为空数组
    }
  },
  computed: {},
  watch: {
    searchHistories: {
      handler: function (val) { // 监听数组变化
        setItem('TouTiao_list', val)
      },
      immediate: true
    }
  },
  created () {},
  methods: {
    UpHistory (v) { // 更新父组件的数据
      this.searchHistories = v
    },
    SearchResult (v) {
      this.onSearch(v)
    },
    onSearch (val) { // 回车触发
      // 更新文本框内容
      this.searchText = val
      // 存储搜索历史记录
      const index = this.searchHistories.indexOf(val)
      // 不能有重复的历史记录、最新的在最前面
      if (index !== -1) { // 说明数组本身已经存在该val
        this.searchHistories.splice(index, 1)
      }
      // 最新的在最前面
      this.searchHistories.unshift(val)
      // 渲染搜索结果 展示结果页面
      this.isResult = true
    },
    onCancel () {
      this.$router.back()
    }
  }
}
</script>

<style scoped lang="less">
.search-container{
.van-search{
  background-color: rgb(251, 91, 216);
}
.searchFrom{
  padding-top: 106px;
  .van-search{
     position: fixed;
     top: 0;
     left: 0;
     right: 0;
     z-index: 1;
  }
  .van-search__action {
        color: #fff;
    }
}
}

</style>
